import { asyncRoutes, constantRoutes } from '@/router'
import intersection from 'lodash/intersection'

// import { getToken } from '@/utils/auth'
// import { SUPER_ADMIN_EMAIL, HR_BP, FINANCE } from '@/utils/const'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    if (route.children) {
      // 判断路由下面的children是否全部都没权限，如果全部没有权限，则不要注册父路由
      // const arr = route.children.map((item) => item.meta.roles[0])
      const arr = []
      route.children.forEach((item) => {
        if (item.meta.roles) {
          arr.push(item.meta.roles[0])
        }
      })
      if (!arr.length) {
        return true
      }
      // 交集
      const interArr = intersection(roles, arr)
      if (interArr.length) {
        return true
      } else {
        return false
      }
    }
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
